import { Provide, Inject, Config } from '@midwayjs/core';
import { JwtService } from '@midwayjs/jwt';
import { LoginDto, RegisterDto } from '../dto/userDto';
import { AuthDao } from '../dao/auth.dao';
import { v4 as uuidv4 } from 'uuid';

@Provide()
export class AuthService {
    @Inject()
    authDao: AuthDao;
    
    @Inject()
    jwtService: JwtService;
    
    @Config('jwtConfig')
    jwtConfig: { secret: string; expiresIn: string };

    // 登录验证方法 - 使用数据库
    async login(loginDto: LoginDto): Promise<{ token?: string; user?: any; message?: string }> {
        const { username, password } = loginDto;
        
        try {
            // 从数据库查找用户
            const user = await this.authDao.validateUser(username, password);
            
            if (user) {
                // 生成JWT token
                const payload = {
                    userId: user.id,
                    username: user.username
                };
                const token = await this.jwtService.sign(payload, this.jwtConfig.secret, {
                    expiresIn: this.jwtConfig.expiresIn as any
                });
                
                console.log(`用户 ${username} 登录成功，生成JWT token`);
                
                return {
                    token: token,
                };
            } else {
                throw new Error('用户名或密码错误');
            }
        } catch (error) {
            console.error('登录过程中发生错误:', error);
            throw new Error(error.message || '登录失败，请稍后重试');
        }
    }

    // 用户注册方法
    async register(registerDto: RegisterDto): Promise<{ success: boolean; message: string; data?: any }> {
        const { username, phone, email, password,name } = registerDto;
        
        try {
            // 检查用户名是否已存在
            const usernameExists = await this.authDao.checkUsernameExists(username);
            if (usernameExists) {
                return {
                    success: false,
                    message: '用户名已存在'
                };
            }

            // 检查邮箱是否已存在
            const emailExists = await this.authDao.checkEmailExists(email);
            if (emailExists) {
                return {
                    success: false,
                    message: '邮箱已被注册'
                };
            }

            // 检查手机号是否已存在
            const phoneExists = await this.authDao.checkPhoneExists(phone);
            if (phoneExists) {
                return {
                    success: false,
                    message: '手机号已被注册'
                };
            }

            // 创建新用户
            const userData = {
                id: uuidv4(),
                username: username,
                password: password, // 实际项目中应该加密
                name:name,
                email: email,
                phone: phone,
            };

            const newUser = await this.authDao.createUser(userData);
            
            console.log(`新用户注册成功: ${username}`);
            
            return {
                success: true,
                message: '注册成功',
                data: {
                    id: newUser.id,
                    username: newUser.username,
                    email: newUser.email,
                    phone: newUser.phone
                }
            };
        } catch (error) {
            console.error('注册过程中发生错误:', error);
            return {
                success: false,
                message: '注册失败，请稍后重试'
            };
        }
    }
}